//
//  BIDSettingsViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/5/17.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDSettingsViewController.h"
#import "BIDSettingForAvatarCell.h"
#import "BIDLoginViewController.h"
#import "BIDSetPortraitViewController.h"
#import "BIDEditPasswordViewController.h"
#import "BIDEditPhoneViewController.h"
#import "BIDEditNickNameViewController.h"
#import "BIDEditGenderViewController.h"
#import "BIDSuggestAboutAPPViewController.h"
#import "BIDAboutViewController.h"
#import "BIDUploadFile.h"
#import "UIImage+BIDImageScale.h"
#import <SDWebImage/UIImageView+WebCache.h>

/**
 *  上传头像
 */
static NSString *uploadPortraitURL = @"/memberAndroid/uploadHead.action";

@interface BIDSettingsViewController ()<UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, BIDSetPortraitViewControllerDelegate, BIDUploadFileDelegate, BIDEditNickNameViewControllerDelegate, BIDEditGenderViewControllerDelegate, BIDEditPhoneViewControllerDelegate>
{
    NSMutableArray *_dataSourceArr;
    BOOL _bRegister;
    UIAlertController *_alert;
    BIDUploadFile *_uploadFile;
    UIImage *_portraitImg;
    NSIndexPath *_selectIndexPath;
    CGRect _oldFrame;
    CGRect _largeFrame;
    CGFloat _originalMaxWidth;
}
@end

@implementation BIDSettingsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"设置";
    [self prepareData];
    //
    _tableView.tableFooterView = [[UIView alloc] init];
    //创建actionSheet
    _alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
    }];
    UIAlertAction *fromCameraAction = [UIAlertAction actionWithTitle:@"从照片库" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        [self fromPhotoLibrary];
    }];
    UIAlertAction *fromPhotoLibraryAction = [UIAlertAction actionWithTitle:@"从相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        [self fromCamera];
    }];
    [_alert addAction:cancelAction];
    [_alert addAction:fromPhotoLibraryAction];
    [_alert addAction:fromCameraAction];
    //创建上传对象
    NSString *strUploadURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], uploadPortraitURL];
    _uploadFile = [[BIDUploadFile alloc] initWithURL:strUploadURL];
    _uploadFile.delegate = self;
    //
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    _originalMaxWidth = screenSize.width;
}

- (void)prepareData
{
    NSDictionary *dic = [AppDelegate getUserDetailInfo];
    NSNumber *genderValue = dic[@"gender"];
    NSString *strGender = @"保密";
    if(genderValue)
    {
        switch([genderValue intValue])
        {
            case 1:
            {
                strGender = @"男";
            }
                break;
            case 2:
            {
                strGender = @"女";
            }
                break;
            case 3:
            {
                strGender = @"保密";
            }
                break;
        }
    }
    NSArray *tempArr = @[@[@{@"title":@"头像", @"content":@""},
                         @{@"title":@"昵称", @"content":dic[@"nickName"]},
                         @{@"title":@"手机号", @"content":dic[@"telephone"]},
                         @{@"title":@"性别", @"content":strGender}],
                       @[@{@"title":@"修改密码", @"content":@""},
                         @{@"title":@"帮助与反馈", @"content":@""},
                         @{@"title":@"分享给好友", @"content":@""},
                         @{@"title":@"关于", @"content":@""}]];
    _dataSourceArr = [[NSMutableArray alloc] initWithArray:tempArr];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 退出登录

 @param sender <#sender description#>
 */
- (IBAction)exitBtnHandler:(id)sender
{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                   message:@"确定要退出吗?"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction * action) {
                                                          }];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              [self exitToLogin];
                                                          }];
    [alert addAction:cancelAction];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)exitToLogin
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:@"" forKey:@"username"];
    [userDefaults setObject:@"" forKey:@"password"];
    [userDefaults synchronize];
    BIDLoginViewController *vc = [[BIDLoginViewController alloc] initWithNibName:@"BIDLoginViewController" bundle:nil];
    [self.navigationController setViewControllers:@[vc] animated:YES];
}

/**
 从相机获取图片
 */
- (void)fromCamera
{
    [self choosePicByWay:0];
}

/**
 从相册获取图片
 */
- (void)fromPhotoLibrary
{
    [self choosePicByWay:1];
}

- (void)choosePicByWay:(NSUInteger)way
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    BOOL bCanUse = NO;
    if(way == 0)
    {
        //从相机
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            [self showAlertView:@"相机不可用" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            bCanUse = YES;
            sourceType = UIImagePickerControllerSourceTypeCamera;
        }
    }
    else if(way == 1)
    {
        //从照片库
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            [self showAlertView:@"照片库不可用" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            bCanUse = YES;
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
    }
    if(bCanUse)
    {
        UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
        pickerController.delegate = self;
        pickerController.sourceType = sourceType;
        [self presentViewController:pickerController animated:YES completion:^{}];
    }
}

/**
 *  点击头像查看大图
 *
 *  @param gestureRecognizer <#gestureRecognizer description#>
 */
- (void)tapGestureHandler:(UITapGestureRecognizer*)gestureRecognizer
{
    if([gestureRecognizer.view isKindOfClass:[UIImageView class]])
    {
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        UIView *showImgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenSize.width, screenSize.height)];
        [showImgView setBackgroundColor:[UIColor blackColor]];
        showImgView.userInteractionEnabled  =  YES;
        CGSize imgViewSize = CGSizeMake(screenSize.width, screenSize.width);
        CGRect imgViewFrame = CGRectMake((screenSize.width-imgViewSize.width)/2, (screenSize.height-imgViewSize.height)/2, imgViewSize.width, imgViewSize.height);
        _oldFrame = imgViewFrame;
        _largeFrame = CGRectMake(0, 0, 3 * _oldFrame.size.width, 3 * _oldFrame.size.height);
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:imgViewFrame];
        imgView.userInteractionEnabled = YES;
        imgView.image = _portraitImg;
        //UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchView:)];
        //[imgView addGestureRecognizer:pinchGestureRecognizer];
        // add pan gesture
        //UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panView:)];
        //[imgView addGestureRecognizer:panGestureRecognizer];
        [showImgView addSubview:imgView];
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        [keyWindow addSubview:showImgView];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
        [showImgView addGestureRecognizer:tapGesture];
    }
    else if([gestureRecognizer.view isKindOfClass:[UIView class]])
    {
        [gestureRecognizer.view removeFromSuperview];
    }
}

#pragma mark BIDUploadFileDelegate
- (void)finishUploadWithResult:(id)obj
{
    if([obj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dic = (NSDictionary*)obj;
        NSNumber *value = dic[@"head"][@"success"];
        if(value)
        {
            if([value intValue] == 1)
            {
                [AppDelegate setUserDetailInfo:dic[@"body"]];
                BIDSettingForAvatarCell *cell = [_tableView cellForRowAtIndexPath:_selectIndexPath];
                cell.imgView.image = _portraitImg;
                [self showHint:@"头像设置成功"];
            }
            else
            {
                [self showHint:@"头像设置失败"];
            }
        }
    }
}

- (void)uploadFailedWithError:(NSError *)err
{
    [self showAlertView:[err localizedDescription] buttonTitle:ALERT_BTN_TITLE tag:@0 functionName:nil];
}

#pragma mark BIDSetPortraitViewControllerDelegate
/**
 *设置图片成功，先校验，然后上传
 */
- (void)finishCropImage:(UIImage *)img viewController:(UIViewController *)viewController
{
    _portraitImg = img;
    //[_myTableView reloadData];
    [viewController dismissViewControllerAnimated:YES completion:^{}];
    [_uploadFile addData:@"photoFileName" value:@"avatar.jpg"];
    NSData *uploadData = UIImageJPEGRepresentation(_portraitImg, 1.0f);
    [_uploadFile addFileFromMemory:@"avatar.jpg" fieldName:@"photo" data:uploadData];
    [_uploadFile addData:@"memberId" value:[AppDelegate getUserId]];
    [_uploadFile finishAddFile];
    [_uploadFile startUpload];
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:NO completion:^{
        UIImage *originalImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        originalImg = [self imageByScalingToMaxSize:originalImg];
        BIDSetPortraitViewController *setPortraitVC = [[BIDSetPortraitViewController alloc] initWithImage:originalImg];
        setPortraitVC.delegate = self;
        [self presentViewController:setPortraitVC animated:YES completion:^{
        }];
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < _originalMaxWidth) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height)
    {
        btHeight = _originalMaxWidth;
        btWidth = sourceImage.size.width * (_originalMaxWidth / sourceImage.size.height);
    }
    else
    {
        btWidth = _originalMaxWidth;
        btHeight = sourceImage.size.height * (_originalMaxWidth / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [UIImage imageCompressForSize:sourceImage targetSize:targetSize];
}

#pragma mark - BIDEditNickNameViewControllerDelegate
- (void)editNickName:(NSString *)nickName atIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:[AppDelegate getUserDetailInfo]];
    [dic setObject:nickName forKey:@"nickName"];
    [AppDelegate setUserDetailInfo:dic];
    [self prepareData];
    [_tableView reloadData];
}

#pragma mark - BIDEditGenderViewControllerDelegate
- (void)editGender:(NSString *)gender atIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:[AppDelegate getUserDetailInfo]];
    [dic setObject:gender forKey:@"gender"];
    [AppDelegate setUserDetailInfo:dic];
    [self prepareData];
    [_tableView reloadData];
}

#pragma mark - BIDEditPhoneViewControllerDelegate
- (void)editPhone:(NSString *)phone
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:[AppDelegate getUserDetailInfo]];
    [dic setObject:phone forKey:@"telephone"];
    [AppDelegate setUserDetailInfo:dic];
    [self prepareData];
    [_tableView reloadData];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSourceArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = _dataSourceArr[section];
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    if(!_bRegister)
    {
        _bRegister = YES;
        UINib *nib = [UINib nibWithNibName:@"BIDSettingForAvatarCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:@"avatar"];
    }
    cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
    NSDictionary *dic = _dataSourceArr[section][row];
    if(section==0 && row==0)
    {
        BIDSettingForAvatarCell *avatarCell = [tableView dequeueReusableCellWithIdentifier:@"avatar"];
        avatarCell.titleLabel.text = dic[@"title"];
        NSDictionary *userDetail = [AppDelegate getUserDetailInfo];
        NSString *strAvatarPath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], userDetail[@"photo"]];
        [avatarCell.imgView setImageWithURL:[NSURL URLWithString:strAvatarPath] placeholderImage:[UIImage imageNamed:@"defaultPortrait.png"] completed:^(UIImage *image, NSError *err, SDImageCacheType cacheType){
            if(!err && image)
            {
                _portraitImg = image;
            }
        }];
        avatarCell.accessoryType = UITableViewCellAccessoryNone;
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
        [avatarCell.imgView addGestureRecognizer:tapGR];
        avatarCell.imgView.userInteractionEnabled = YES;
        cell = avatarCell;
    }
    else
    {
        cell.textLabel.text = dic[@"title"];
        cell.detailTextLabel.text = dic[@"content"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    NSDictionary *dic = _dataSourceArr[section][row];
    _selectIndexPath = indexPath;
    switch(section)
    {
        case 0:
        {
            if(row == 0)
            {
                //设置头像
                [self presentViewController:_alert animated:YES completion:nil];
            }
            else if(row == 1)
            {
                //修改昵称
                BIDEditNickNameViewController *vc = [[BIDEditNickNameViewController alloc] initWithNibName:@"BIDEditNickNameViewController" bundle:nil];
                vc.content = dic[@"content"];
                vc.delegate = self;
                vc.indexPath = indexPath;
                [self.navigationController pushViewController:vc animated:YES];
            }
            else if(row == 2)
            {
                //修改手机号
                BIDEditPhoneViewController *vc = [[BIDEditPhoneViewController alloc] initWithNibName:@"BIDEditPhoneViewController" bundle:nil];
                vc.delegate = self;
                [self.navigationController pushViewController:vc animated:YES];
            }
            else if(row == 3)
            {
                //修改性别
                BIDEditGenderViewController *vc = [[BIDEditGenderViewController alloc] init];
                vc.delegate = self;
                vc.gender = dic[@"content"];
                vc.selectIndexPath = indexPath;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
        case 1:
        {
            if(row == 0)
            {
                //修改密码
                BIDEditPasswordViewController *vc = [[BIDEditPasswordViewController alloc] initWithNibName:@"BIDEditPasswordViewController" bundle:nil];
                [self.navigationController pushViewController:vc animated:YES];
            }
            else if(row == 1)
            {
                //意见反馈
                BIDSuggestAboutAPPViewController *vc = [[BIDSuggestAboutAPPViewController alloc] initWithNibName:@"BIDSuggestAboutAPPViewController" bundle:nil];
                [self.navigationController pushViewController:vc animated:YES];
            }
            else if(row == 2)
            {}
            else if(row == 3)
            {
                //关于
                BIDAboutViewController *vc = [[BIDAboutViewController alloc] initWithNibName:@"BIDAboutViewController" bundle:nil];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 44.f;
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    if(section==0 && row==0)
    {
        height = 60.f;
    }
    return height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = nil;
    headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 10.f)];
    [headerView setBackgroundColor:RGBACOLOR(239.f, 239.f, 239.f, 1.f)];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0)
        return 0.f;
    return 10.f;
}

@end
